// pages/navigator/filter/index.js
const app = getApp()

Page({

  /**
   * Page initial data
   */
  data: {
    planTotal:'',
    realTotal:'',
    query:'',
    banner:{},
    currentIndex: '1', // 默认选中第一个
    orders:[], // 原始订单数据
    ordersFilter:[], // 筛选后的订单数据
    phone:wx.getStorageSync('phone'),
    percent:'90',
    userphone:'',
    password:'',
    showAuthPopup: false,
    showAuthPopup2:false,
    currentNumber:'',
    maxNumber:'',
    realNumber:'',
    currentOrderId:'',
    currentOrderWorkerId:'',
    currentOrderProcessId:'',
    listData:[],
    listFlag:false,
    // 月份筛选相关
    selectedMonth: new Date().getMonth() + 1, // 默认当前月份
    selectedYear: new Date().getFullYear(), // 默认当前年份
    monthOptions: [], // 月份选项数组
    // 分页相关
    pageSize: 10,
    loading: false,
    hasMore: true,
    currentPage: 1,
    // 防止重复提交
    submitting: false
  },
  showList(e){
    this.setData({
      currentOrderProcessId:e.currentTarget.dataset.name,
      currentOrderWorkerId:e.currentTarget.dataset.id,
      currentOrderId:e.currentTarget.dataset.type,
      listFlag:true
    })
    this.selctWorkerList()
  },
  onClosePopup3(){
    this.setData({ listFlag: false });
  },
  queryInput(e){
    console.log(e.detail.value)
    this.setData({
      query: e.detail.value,
      currentPage: 1,
      orders: [],
      ordersFilter: [],
      hasMore: true
    });
    this.getOrder(false);
  },
  // 月份筛选方法
  selectMonth(e){
    const monthIndex = parseInt(e.currentTarget.dataset.index);
    
    // 如果索引有效，使用新格式
    if (!isNaN(monthIndex) && this.data.monthOptions && this.data.monthOptions[monthIndex]) {
      const monthOption = this.data.monthOptions[monthIndex];
      
      if (monthOption && typeof monthOption === 'object') {
        // 新格式：包含month和year的对象
        this.setData({
          selectedMonth: parseInt(monthOption.month),
          selectedYear: parseInt(monthOption.year),
          currentPage: 1,
          orders: [],
          ordersFilter: [],
          hasMore: true
        });
      } else {
        // 月份选项是数字
        const selectedMonth = monthOption;
        const now = new Date();
        const currentYear = now.getFullYear();
        // 如果选择的月份大于当前月份，说明是去年的
        const selectedYear = selectedMonth > now.getMonth() + 1 ? currentYear - 1 : currentYear;
        
        this.setData({
          selectedMonth: parseInt(selectedMonth),
          selectedYear: parseInt(selectedYear),
          currentPage: 1,
          orders: [],
          ordersFilter: [],
          hasMore: true
        });
      }
    } else {
      // 兼容旧格式：直接从data-month获取
      const selectedMonth = parseInt(e.currentTarget.dataset.month);
      if (!isNaN(selectedMonth)) {
        const now = new Date();
        const currentYear = now.getFullYear();
        // 如果选择的月份大于当前月份，说明是去年的
        const selectedYear = selectedMonth > now.getMonth() + 1 ? currentYear - 1 : currentYear;
        
        this.setData({
          selectedMonth: parseInt(selectedMonth),
          selectedYear: parseInt(selectedYear),
          currentPage: 1,
          orders: [],
          ordersFilter: [],
          hasMore: true
        });
      }
    }
    
    // 重新请求对应月份的数据
    this.getOrder(false);
    this.getBanner();
  },
  // 初始化月份选项
  initMonthOptions(){
    const now = new Date();
    const currentMonth = now.getMonth() + 1;
    const currentYear = now.getFullYear();
    const monthOptions = [];
    
    // 生成最近6个月的选项，包含月份和年份信息
    for(let i = 0; i < 6; i++){
      let date = new Date(currentYear, currentMonth - i - 1, 1);
      let month = date.getMonth() + 1;
      let year = date.getFullYear();
      monthOptions.push({
        month: month,
        year: year,
        display: `${month}月`,
        value: month
      });
    }
    
    this.setData({
      monthOptions: monthOptions,
      selectedMonth: parseInt(currentMonth),
      selectedYear: parseInt(currentYear)
    });
    console.log('月份选项初始化:', {
      monthOptions: monthOptions,
      selectedMonth: parseInt(currentMonth),
      selectedYear: parseInt(currentYear)
    });
  },
  loginModal() {
    this.setData({ showAuthPopup: true });
  },
  logout(){
    wx.setStorageSync('phone','')
    this.setData({ 
      phone:'',
      showAuthPopup: false });
      this.getOrder(false)
      this.getBanner()  

  },
  login(){
    if(!this.data.userphone || !/^1[3456789]\d{9}$/.test(this.data.userphone)){
      wx.showToast({
        title: '请输入正确的账号',
        icon: 'none'
      });
      return
    }
    if(!this.data.password){
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return
    }
      let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/loginMini',
          method: 'POST',
          data: {
            phone:_this.data.userphone,
            password:_this.data.password
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data;
            if(data.code==1){
              if(data.data.admin==1){
                wx.setStorageSync('phone',_this.data.userphone)
                wx.setStorageSync('admin',true)
                wx.setStorageSync('uid',data.data.uid)
                _this.setData({ 
                  phone:_this.data.userphone,
                  showAuthPopup: false });
                wx.switchTab({
                  url: '/pages/navigator/index/index',
                });
              }else{
                wx.setStorageSync('phone',_this.data.userphone)
                wx.setStorageSync('admin',false)
                wx.setStorageSync('uid',data.data.uid)
                _this.getOrder(false)
                _this.getBanner()
                _this.setData({ 
                  phone:_this.data.userphone,
                  showAuthPopup: false 
                });
              }
              
            }else{
              wx.showToast({
                title: data.msg,
                icon: 'none'
              });
            }
          },
          fail: function (err) {
          }
        }); 

    
  },
  addNumber(e){
    let _this=this;
    wx.request({
          url: app.globalData.onlineUrl+'/getWorkloadByProcessId',
          method: 'POST',
          data: {
            orderProcessId:e.currentTarget.dataset.name,
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
             _this.setData({
              planTotal:res.data.data.planTotal,
              realTotal:res.data.data.realTotal,
              currentOrderProcessId:e.currentTarget.dataset.name,
              currentOrderWorkerId:e.currentTarget.dataset.id,
              currentNumber:'',
              maxNumber:e.currentTarget.dataset.index,
              realNumber:e.currentTarget.dataset.xindex,
              currentOrderId:e.currentTarget.dataset.type,
              showAuthPopup2:true
            })
          },
          fail: function (err) {
          }
        }); 
  },
  //
  insertList(){
    if(!/^[0-9]+$/.test(String(this.data.currentNumber))){
      wx.showToast({
        title: '请输入正确的数字格式',
        icon: 'none'
      });
      return
    }

    if(Number(this.data.currentNumber)==0){
      wx.showToast({
        title: '请输入工作量',
        icon: 'none'
      });
      return
    }

    // 防止重复提交
    if(this.data.submitting){
      wx.showToast({
        title: '正在提交中，请稍候...',
        icon: 'none',
        duration: 2000
      });
      return
    }
    
    let _this=this;
    const newNumber = Number(this.data.currentNumber);
    
    // 前端预检查：先获取当前总量，检查是否会超出限制
    wx.request({
      url: app.globalData.onlineUrl+'/getWorkloadByProcessId',
      method: 'POST',
      data: {
        orderProcessId: this.data.currentOrderProcessId,
      },
      header: {'content-type': 'application/json' },
      success: function (res) {
        if (res.data.code === 1) {
          const planTotal = res.data.data.planTotal || 0;
          const currentTotal = res.data.data.realTotal || 0;
          const remaining = planTotal - currentTotal;
          
          console.log('前端检查:', {
            planTotal: planTotal,
            currentTotal: currentTotal,
            newNumber: newNumber,
            remaining: remaining
          });
          
          // 前端检查：如果超出限制，直接不调用接口
          if (currentTotal + newNumber > planTotal) {
            wx.showToast({
              title: `超过工序计划总量！计划总量：${planTotal}，当前已录入：${currentTotal}，剩余可录入：${remaining}，本次录入：${newNumber}`,
              icon: 'none',
              duration: 4000
            });
            return;
          }
          
          // ✅ 通过前端检查，调用后端接口（后端还会再次检查，双重保护）
          _this.setData({ submitting: true });
          wx.request({
            url: app.globalData.onlineUrl+'/insertWorkerNumber',
          method: 'POST',
          data: {
            orderId:_this.data.currentOrderId,
            processId:_this.data.currentOrderProcessId,
            workerId:_this.data.currentOrderWorkerId,
            number:_this.data.currentNumber
          },
            header: {'content-type': 'application/json' },
            success: function (res) {
              // 重置提交状态
              _this.setData({ submitting: false });
            
              if (res.data.code === 1) {
                console.log(99988,res.data.data.totalNumber);
                _this.updateNumber(res.data.data.totalNumber);
                
                // 检查是否完成并显示详细信息
                if (res.data.isCompleted) {
                  wx.showToast({
                    title: '工序已完成，订单状态已更新！',
                    icon: 'success',
                    duration: 2000
                  });
                } else {
                  // 显示剩余可录入数量
                  const completeInfo = res.data.processCompleteInfo || {};
                  const remaining = completeInfo.remaining || 0;
                  if (remaining > 0) {
                    wx.showToast({
                      title: `录入成功！工序剩余 ${remaining} 可录入`,
                      icon: 'success',
                      duration: 2000
                    });
                  } else {
                    wx.showToast({
                      title: '录入成功',
                      icon: 'success',
                      duration: 2000
                    });
                  }
                }
                // 刷新数据
                _this.getBanner();
              } else {
                wx.showToast({
                  title: res.data.msg || '录入失败',
                  icon: 'none',
                  duration: 4000
                });
              }
            },
            fail: function (err) {
              // 重置提交状态
              _this.setData({ submitting: false });
              
              console.error('录入工人数量失败:', err);
              wx.showToast({
                title: '网络错误，请重试',
                icon: 'none',
                duration: 3000
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取工序信息失败',
            icon: 'none',
            duration: 3000
          });
        }
      },
      fail: function (err) {
        console.error('获取工序信息失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none',
          duration: 3000
        });
      }
    }); 
  },
  delete(e){
    let _this=this;
  wx.showModal({
    title: '提示',
    content: '确定要删除吗？',
    success: function (sm) {
      if (sm.confirm) {
        wx.request({
          url: app.globalData.onlineUrl+'/deleteWorkerList',
          method: 'POST',
          data: {
           id:e.currentTarget.dataset.id,
           number:e.currentTarget.dataset.index,
           orderWorkerId:_this.data.currentOrderWorkerId
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            if (res.data.code === 1) {
              _this.selctWorkerList();
              _this.getOrder(false)
            } else {
              wx.showToast({
                title: res.data.msg || '删除失败',
                icon: 'none',
                duration: 3000
              });
            }
          },
          fail: function (err) {
            console.error('删除工人记录失败:', err);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none',
              duration: 3000
            });
          }
        }); 
      }
    }
  })
  },
  selctWorkerList(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/selctWorkerList',
          method: 'POST',
          data: {
            orderId:_this.data.currentOrderId,
            processId:_this.data.currentOrderProcessId,
            workerId:_this.data.currentOrderWorkerId,
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            _this.setData({ listData: res.data.data });
          },
          fail: function (err) {
          }
        }); 
  },
  updateNumber(number){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/updateWorkerNumber',
          method: 'POST',
          data: {
            orderId:_this.data.currentOrderId,
            id:_this.data.currentOrderWorkerId,
            realNumber:number
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            console.log('更新工人数量返回:', res);
            if (res.data.code === 1) {
              // 检查是否完成并显示详细信息
              if (res.data.isCompleted) {
                wx.showToast({
                  title: '工序已完成，订单状态已更新！',
                  icon: 'success',
                  duration: 2000
                });
              } else {
                // 显示剩余可录入数量
                const completeInfo = res.data.processCompleteInfo || {};
                const remaining = completeInfo.remaining || 0;
                wx.showToast({
                  title: `更新成功！工序剩余 ${remaining} 可录入`,
                  icon: 'success',
                  duration: 2000
                });
              }
              _this.setData({ showAuthPopup2: false });
              _this.getOrder(false);
              _this.getBanner();
            } else {
              wx.showToast({
                title: res.data.msg || '更新失败',
                icon: 'none',
                duration: 4000
              });
            }
          },
          fail: function (err) {
            console.error('更新工人数量失败:', err);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none',
              duration: 3000
            });
          }
        }); 
  },
  onClosePopup2() {
    this.setData({ showAuthPopup2: false });
  },
  userphoneInput(e){
    let value = e.detail.value;
    this.data.userphone=value
    this.setData({
      userphone:this.data.userphone
   })
  },
  currentNumberInput(e){
    let value = e.detail.value;
    this.data.currentNumber=value
    this.setData({
      currentNumber:this.data.currentNumber
   })
  },
  passwordInput(e){
    let value = e.detail.value;
    this.data.password=value
    this.setData({
      password:this.data.password
   })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },
  switchTab(e){
    this.setData({
      currentIndex:e.currentTarget.dataset.index,
      currentPage: 1,
      orders: [],
      ordersFilter: [],
      hasMore: true
    });
    this.getOrder(false);
  },
  getBanner(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/getOrderBannerByphone',
          method: 'POST',
          data: {
            id:wx.getStorageSync('uid')
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data.data;
            _this.setData({
              banner: data[0]
            })
          },
          fail: function (err) {
          }
        }); 
    
  },
  getOrder(isLoadMore = false){
    let _this=this;
    const selectedMonth = this.data.selectedMonth;
    const selectedYear = this.data.selectedYear || new Date().getFullYear();
    const currentPage = isLoadMore ? this.data.currentPage + 1 : 1;
    
    // 防止重复请求
    if(this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    console.log('请求参数:', {
      month: selectedMonth,
      year: selectedYear,
      page: currentPage,
      pageSize: this.data.pageSize,
      isLoadMore: isLoadMore,
      workerId: wx.getStorageSync('uid')
    });
    
    wx.request({
      url: app.globalData.onlineUrl+'/getOrderByphone',
      method: 'POST',
      data: {
        id: wx.getStorageSync('uid'),
        month: selectedMonth,
        year: selectedYear,
        page: currentPage,
        pageSize: this.data.pageSize,
        state: this.data.currentIndex,
        query: this.data.query
      },
      header: {'content-type': 'application/json' }, // 请求头
      success: function (res) {
        let data = res.data.data || [];
        console.log('返回数据:', {
          dataLength: data.length,
          pageSize: _this.data.pageSize,
          currentPage: currentPage,
          isLoadMore: isLoadMore
        });
        
        // 前端去重：确保每个订单只显示一次（使用Map按orderId去重）
        const orderMap = new Map();
        data.forEach(order => {
          if (order.orderId && !orderMap.has(order.orderId)) {
            orderMap.set(order.orderId, order);
          }
        });
        const deduplicatedData = Array.from(orderMap.values());
        
        let newOrders = isLoadMore ? [..._this.data.orders, ...deduplicatedData] : deduplicatedData;
        
        // 再次去重合并后的数据
        const finalOrderMap = new Map();
        newOrders.forEach(order => {
          if (order.orderId && !finalOrderMap.has(order.orderId)) {
            finalOrderMap.set(order.orderId, order);
          }
        });
        const finalOrders = Array.from(finalOrderMap.values());
        
        console.log('数据合并:', {
          isLoadMore: isLoadMore,
          oldOrdersLength: _this.data.orders.length,
          newDataLength: data.length,
          deduplicatedLength: deduplicatedData.length,
          finalLength: finalOrders.length
        });
        
        _this.setData({
          orders: finalOrders,
          ordersFilter: finalOrders,
          currentPage: currentPage,
          loading: false,
          hasMore: deduplicatedData.length === _this.data.pageSize
        });
        
        console.log('更新后状态:', {
          ordersLength: newOrders.length,
          hasMore: data.length === _this.data.pageSize
        });
      },
      fail: function (err) {
        console.log('获取订单数据失败:', err);
        _this.setData({
          loading: false
        });
      }
    }); 
  },
  loadMoreData: function() {
    if (!this.data.loading && this.data.hasMore) {
      this.getOrder(true);
    }
  },
  gotoOrderDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log(1234567,id)
    wx.navigateTo({
      url: '/pages/navigator/filterDetail/index?id='+id
    });
  },
  add(e){
    wx.navigateTo({
      url: '/pages/navigator/filterAdd/index?id='+e.currentTarget.dataset.id
    });
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function() {
    // 初始化月份选项，不依赖登录状态
    this.initMonthOptions();
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {
    let admin=wx.getStorageSync('admin')
    let phone=wx.getStorageSync('phone')
    if(admin){
      wx.switchTab({
        url: '/pages/navigator/index/index',
      });
    }else{
      if(phone){
        // 确保月份选项已初始化（防止某些情况下未初始化）
        if(!this.data.monthOptions || this.data.monthOptions.length === 0){
          this.initMonthOptions();
        }
        // 重置分页状态
        this.setData({
          currentPage: 1,
          orders: [],
          ordersFilter: [],
          hasMore: true
        });
        this.getOrder(false);
        this.getBanner();
      }
     
    }
    
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function() {

  }
});
